package models

import (
	"github.com/astaxie/beego/config"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var (
	Dao *xorm.Engine
)

func init() {
	Dao = NewDAO()
}

// NewDAO 初始化数据库连接
func NewDAO() *xorm.Engine {
	dbType := "mysql"
	dns := getMysqlDns()

	dao, err := xorm.NewEngine(dbType, dns)
	// dao.ShowSQL()

	if err != nil {
		panic(err)
		return nil
	}

	Dao = dao
	return dao
}

func getMysqlDns() string {
	dbconf, _ := config.NewConfig("ini", "conf/db.conf")

	// db_type  := dbconf.DefaultString("db_type", "mysql")
	conProt := dbconf.DefaultString("con_protocol", "tcp")
	dbAddr := dbconf.DefaultString("db_addr", "localhost")
	dbPort := dbconf.DefaultString("db_port", "3306")
	userName := dbconf.DefaultString("username", "root")
	password := dbconf.String("password")
	database := dbconf.String("database")
	// dbprefix := dbconf.String("dbprefix")
	// db_debug := dbconf.DefaultBool("db_debug", false)
	charSet := dbconf.DefaultString("char_set", "utf8")

	dns := userName

	if len(password) > 0 {
		dns += ":" + password
	}

	dns += "@" + conProt + "(" + dbAddr + ":" + dbPort + ")" + "/" + database + "?charset=" + charSet

	return dns
}
